# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def longestZigZag(self, root: Optional[TreeNode]) -> int:
        def dfs(node: Optional[TreeNode], length: int, is_left: bool):
            if not node:
                return 
            self.longest = max(self.longest, length)

            dfs(node.left, 1 if is_left else length + 1, True)
            dfs(node.right, 1 if not is_left else length + 1, False)
        self.longest = 0
        dfs(root, 0, True)
        return self.longest